package com.jintian.smart.kernel.common.expr;

import com.jintian.smart.kernel.common.util.NumberUtil;
import com.jintian.smart.kernel.core.annotation.expr.ExprFn;
import com.jintian.smart.kernel.core.annotation.expr.ExprFns;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.Collection;
import java.util.Map;
import java.util.UUID;

@ExprFn(code = "")
public class CommonFn {
    public static Object iif(boolean condition, Object trueValue, Object falseValue) {
        return condition ? trueValue : falseValue;
    }

    public static String subString(String obj, int... pos) {
        if (pos.length == 1)
            return obj.substring(pos[0]);
        else
            return obj.substring(pos[0], pos[1]);
    }

    @ExprFns({@ExprFn(code = "common.guid"), @ExprFn(code = "guid")})
    public static String guid() {
        return UUID.randomUUID().toString().replaceAll("\\-", "");
    }

    public static int length(Object obj) {
        if (obj == null)
            return 0;
        if (obj instanceof String) {
            return ((String) obj).length();
        }
        if (obj instanceof Collection)
            return ((Collection) obj).size();
        if (obj instanceof Map)
            return ((Map) obj).size();
        throw new IllegalArgumentException("length函数不支持类型为" + obj.getClass() + "的参数");
    }

    public static String concat(Object... args) {
        StringBuffer sb = new StringBuffer();
        for (Object s : args) {
            sb.append(s);
        }
        return sb.toString();
    }

    public static Number add(Number a1, Number a2) {
        return a1.doubleValue() + a2.doubleValue();
    }

    public static int toInt(Object value) {
        if (value == null)
            return 0;
        if (value instanceof Number) {
            return ((Number) value).intValue();
        }
        return NumberUtil.toInt(value.toString());
    }

    public static BigDecimal toDecimal2(Object obj) throws ParseException {
        return toDecimal(obj, null);
    }

    public static BigDecimal toDecimal(Object obj, Integer scale) throws ParseException {
        if (obj == null)
            return null;
        if ((obj instanceof BigDecimal)) {
            return (BigDecimal) obj;
        }
        BigDecimal ret = null;
        if (obj instanceof String) {
            String str = obj.toString();
            if (str.toUpperCase().contains("E")) {
                ret = new BigDecimal(new DecimalFormat().parse(str).doubleValue());
            } else {
                ret = new BigDecimal(str);
            }
        } else if ((obj instanceof Number)) {
            ret = new BigDecimal(((Number) obj).doubleValue());
        } else {
            throw new IllegalArgumentException(obj + "不能转换为BigDecimal");
        }
        if (scale != null) {
            return ret.setScale(scale, RoundingMode.HALF_UP);
        }
        return ret;
    }

}
